package com.niit.mobileDevide.userbehaviorclass;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class DevideUserbehaviorClassMapper extends Mapper<LongWritable, Text, Text, Text> {

    // 定义各字段的索引位置
    private static final int USER_BEHAVIOR_CLASS_INDEX = 10; // 用户行为分类
    private static final int APP_USAGE_TIME_INDEX = 3; // 应用程序使用时间
    private static final int SCREEN_ON_TIME_INDEX = 4; // 屏幕开启时间
    private static final int BATTERY_DRAIN_INDEX = 5; // 电池消耗
    private static final int NUM_APPS_INSTALLED_INDEX = 6; // 已安装应用数量
    private static final int DATA_USAGE_INDEX = 7; // 数据使用量

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        // 打印输入行，方便调试
        System.out.println("Processing line: " + value);

        // 忽略标题行（可选）
        if (key.get() == 0) return;

        String[] columns = value.toString().split(",");
        if (columns.length < 8) { // 确保至少有8个字段
            System.err.println("Skipping line due to insufficient fields: " + value);
            return;
        }

        try {
            // 使用用户行为分类作为key
            String userBehaviorClass = columns[USER_BEHAVIOR_CLASS_INDEX].trim().toLowerCase();
            if (!"1".equals(userBehaviorClass) && !"2".equals(userBehaviorClass) && !"3".equals(userBehaviorClass) && !"4".equals(userBehaviorClass) && !"5".equals(userBehaviorClass) ) {
                System.err.println("Invalid user behavior class: " + userBehaviorClass + ". Skipping line.");
                return;
            }

            // 组合需要统计的值作为value，使用默认值0替换空字段
            StringBuilder record = new StringBuilder();
            for (int i : new int[]{APP_USAGE_TIME_INDEX, SCREEN_ON_TIME_INDEX, BATTERY_DRAIN_INDEX, NUM_APPS_INSTALLED_INDEX, DATA_USAGE_INDEX}) {
                String field = columns.length > i ? columns[i].trim() : "";
                double fieldValue = field.isEmpty() ? 0.0 : Double.parseDouble(field);
                record.append(fieldValue).append(",");
            }
            record.setLength(record.length() - 1); // 去掉最后一个逗号

            // 写入键值对
            context.write(new Text(userBehaviorClass), new Text(record.toString()));
        } catch (NumberFormatException e) {
            // 跳过格式错误的行，并打印错误信息
            System.err.println("Error parsing line: " + value + ". Error: " + e.getMessage());
        }
    }
}